<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/12
 * Time: 12:47
 */

namespace app\admin\controller;


use app\admin\behaviour\AdminAuth;
use app\admin\model\ApiResponse;
use app\admin\model\SysAdmin;
use app\admin\model\SysAdminMenu;
use app\admin\lib\AdminController;
use app\common\model\teacher\Teacher;
use app\common\lib\rongcloud\RongCloud;
use app\common\model\Chat;
use think\Db;
use think\exception\HttpResponseException;
use think\Request;

class Account extends AdminController
{
    /**
     * 登录
     *
     * @return ApiResponse
     */
    public function login() {

        $form = $this->getAndCheckForm([
            ['account', 'require',],
            ['password', 'require',],
        ]);

        $admin = $this->doLogin($form['account'], $form['password']);

        $token = AdminAuth::setToken($admin->id);
        $data = $admin->toArray();
        unset($data['password']);
        $data['token'] = $token;
        $data['created'] = substr($data['created'],0,10);

        return ApiResponse::success($data);
    }

    /**
     * 修改密码
     *
     * @param Request $request
     * @return ApiResponse
     */
    public function update_password(Request $request) {

        $form = $this->getAndCheckForm([
            ['password_old', 'require', '旧密码不能为空'],
            ['password_new', 'require', '新密码不能为空'],
        ]);
        if ($form['password_old'] == $form['password_new']) {
            ApiResponse::success('新旧密码相同');
        }

        $admin = SysAdmin::get($request->adminId);
        if (empty($admin)) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'旧密码错误');
        }
        $hash_old = passEncrypt($form['password_old']);
        if ($hash_old !== $admin->password) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'旧密码错误');
        }
        $hash_new = passEncrypt($form['password_new']);
        $admin->password = $hash_new;
        $admin->save();

        return ApiResponse::success();
    }

    /**
     * 聊天登录接口，直接返回聊天token
     *
     * @return array
     */
    public function customer_service_login() {

        $form = $this->getAndCheckForm([
            ['account', 'require',],
            ['password', 'require',],
        ]);

        $admin = $this->doLogin($form['account'], $form['password']);
        $cs = Db::table('customer_service')
            ->where('admin_id','=', $admin->id)
            ->field('admin_id')
            ->find();
        if (empty($cs))
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'您不是客服');

        $chat = $admin->serviceChatToken();

        return ['code'=>200, 'chat' => $chat];
    }

    /**
     * 聊天窗口获取用户信息接口
     *
     * @return ApiResponse
     */
    public function get_chat_user_info() {

        $id = input('post.id');

        $info = Chat::getUserInfo($id);
        if ($info) return ApiResponse::success($info);
        else return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'用户不存在');
    }

    /**
     * 获取用户在线状态
     * @return ApiResponse
     */
    public function check_chat_user_online() {

        $id = input('post.id');
        $info = Chat::getUserInfo($id);
        if ($info) {
            $re = RongCloud::getInstance()->User()->checkOnline($info['id']);
            if ($re)
                return ApiResponse::success(['online' => $re['status']]);
        }
        return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'用户不存在');
    }

    /**
     * 提供老师登录聊天室
     *
     * @return array
     */
    public function teacher_chat_login() {
        $name = input('post.name');
        $teacher = Db::table('teacher')->where('name', '=', $name)->find();
        if (empty($teacher)) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'教师不存在');
        }
        $chat = Teacher::chatToken($teacher);
        return ['code'=>200, 'chat' => $chat];
    }

    /**
     * @deprecated
     * 教师列表
     * @return ApiResponse
     */
    public function teacher_names() {
        $list = Teacher::listNames();
        return ApiResponse::success($list);
    }

    /**
     * 获取用户并验证密码
     *
     * @param $account
     * @param $password
     * @return SysAdmin
     * @throws HttpResponseException
     */
    private function doLogin($account, $password) {

        $admin = SysAdmin::getByName($account);
        if (empty($admin)) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'帐号或密码错误');
        }
        $hash = passEncrypt($password);
        if ($hash !== $admin->password) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'帐号或密码错误');
        }

        return $admin;
    }

    /**
     * 返回角色的菜单树
     *
     * @param Request $request
     * @return ApiResponse
     */
    public static function menu_tree(Request $request) {
        if ($request->adminId > 1) {
            $admin = SysAdmin::get($request->adminId);
            $list = SysAdminMenu::menuTree($admin->role_id);
        } else {
            $list = SysAdminMenu::menuAllTree();
            foreach ($list as & $item) {
                if ($item['id'] === 8) {
                    $item['children'][] = [
                        'link' => '#admin-menu',
                        'title' => '管理菜单',
                        'theme' => '{"class":"fa fa-gears"}',
                        'rank' => 256,
                    ];
                }
            }
        }

        return ApiResponse::success($list);
    }

}